#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

using namespace LogModule;

using func_t = std::function<std::string(const std::string &)>;

const int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t task)
        : _sockfd(defaultfd), _port(port), _isrunning(false), _task(task)
    {
    }

    void Init()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATEL) << "socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd: " << _sockfd;
        // 2.绑定socket信息，ip和端口
        // 2.1 填充sockaddr_in结构体
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        // 我会不会把我的ip地址和端口号发送给对方？ yes
        // IP信息和端口信息，一定要发送到网络！
        local.sin_port = htons(_port);
        // ip也是如此
        // 本地格式->网络序列 1. ip->4字节 2. 4字节->网络序列
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATEL) << "bind error!";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd: " << _sockfd;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 1.接收消息
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (s > 0)
            {
                buffer[s] = 0;
                uint16_t peer_port = peer.sin_port;
                std::string peer_ip = inet_ntoa(peer.sin_addr);
                LOG(LogLevel::DEBUG) << "[" << peer_ip << ": " << peer_port << "]# " << buffer;
                // 2.处理消息
                std::string result = _task(buffer);
                // std::string echo_string = "server echo@ ";
                // echo_string += buffer;
                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~UdpServer() {}

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip; // 点分十进制，方便日志打印 “196.168.1.1”

    bool _isrunning;

    func_t _task; // server收到client的数据，进行处理
};
